import { useEffect, useState } from "react";
import { Table, Tag, Tooltip, Pagination, message, Modal } from "antd";
import { DownOutlined, UpOutlined } from "@ant-design/icons";
import dayjs from "dayjs";
import { Nav } from "@/components/func";
import { recordListGet, recordListDelete } from "@/assets/js/networkRequest/method";
import "./index.less";

const { confirm } = Modal;

// 保存列表数据
let initFormData: any = [];
let current: number = 1;
let limit: number = 10;
let total: number = 0;
let page_total: number = 0;

const AddUserRecord = () => {
  const [, setRender] = useState(0);
  const [loding, setLoding] = useState(true);

  // 每次去请求数据
  const requestRecord = async () => {
    setLoding(true);
    let res: any = await recordListGet({ current, limit });
    setLoding(false);
    if (res.code === 200) {
      res.data.record_info.map((item: any, index: number) => {
        item.key = index;
        item.flag = false;
      });
      total = res.data.record_total;
      page_total = res.data.page_tatal;
      initFormData = res.data.record_info;
      setRender(Math.random() + 1);
    }
  };

  // 删除信息弹窗
  const delWarning = (text: any) => {
    confirm({
      title: "提示",
      icon: null,
      content: `确定删除客户[${text.id}]？`,
      okText: "确认",
      okType: "danger",
      cancelText: "取消",
      onOk() {
        recordListDelete({ id: text.id }).then((res: any) => {
          console.log(res);
          if (res.code === 200) {
            message.info("删除成功");
            requestRecord();
          } else {
            message.info("删除失败");
          }
        });
      },
    });
  };

  // 表头信息
  const columns = [
    {
      title: "名称",
      width: 260,
      dataIndex: "file_name",
    },
    {
      title: "上传时间",
      width: 200,
      dataIndex: "upload_date",
      render: (text: string) => dayjs(text).format("YYYY-MM-DD HH:mm"),
    },
    {
      title: "分配客服",
      width: 200,
      render: (text: any) => {
        return (
          <>
            <div className={`${!text.flag ? "overflow-hidden max-h-68" : ""}`}>
              {text.distribution_employee_id.map((item: any) => {
                return (
                  <div key={item}>
                    <Tag
                      className="leading-8 break-normal whitespace-normal bg-white mb-4 text-xs border-grey-200 text-grey-800 mr-10"
                      icon={
                        <i className="iconfont icon-zhanghaoguanli text-blue-acd7ff mr-5"></i>
                      }
                      color="#fff">
                      {item}
                    </Tag>
                  </div>
                );
              })}
            </div>
            {text.distribution_employee_id.length > 2 ? (
              <div
                className="text-grey-600 cursor-pointer"
                onClick={() => {
                  text.flag = !text.flag;
                  setRender(Math.random() + 1);
                }}>
                {!text.flag ? (
                  <span>
                    展开
                    <DownOutlined />
                  </span>
                ) : (
                  <span>
                    收起
                    <UpOutlined />
                  </span>
                )}
              </div>
            ) : null}
          </>
        );
      },
    },
    {
      title: "客户标签",
      width: 200,
      dataIndex: "customer_tag",
      render: (text: any) => {
        if (text && !text.length) {
          return "-";
        }
        return (
          <>
            {text.map((item: any) => {
              return (
                <Tag
                  key={item}
                  color="#fff"
                  className="leading-8 break-all whitespace-normal bg-white mb-4 text-xs border-grey-200 text-grey-800 mr-10">
                  {item}
                </Tag>
              );
            })}
          </>
        );
      },
    },
    {
      title: "导入客户数",
      width: 165,
      dataIndex: "import_customer_count",
      render: (text: number) => text,
    },
    {
      title: "已添加客户数",
      width: 165,
      dataIndex: "import_customer_pass",
      render: (text: string) => text,
    },
    {
      title: "添加完成率",
      width: 165,
      render: (text: any) =>
        `${(
          (text.import_customer_count
            ? text.import_customer_pass / text.import_customer_count
            : 1) * 100
        ).toFixed(2)}%`,
    },
    {
      title: "操作",
      width: 119,
      render: (text: any) => {
        return (
          <div className="flex text-blue-default">
            {text.import_customer_count === 0 ||
            text.import_customer_pass / text.import_customer_count === 1 ? (
              <Tooltip
                color="#fff"
                placement="top"
                title={<p className="text-grey-800">客户已添加完成</p>}>
                <span className="py-0 px-8 leading-none whitespace-nowrap border-r-1 border-solid border-grey-200 h-auto text-grey-400 cursor-default">
                  提醒
                </span>
              </Tooltip>
            ) : (
              <span className="cursor-pointer py-0 px-8 leading-none whitespace-nowrap border-r-1 border-solid border-grey-200 h-auto">
                提醒
              </span>
            )}
            <span
              className="cursor-pointer py-0 px-8 leading-none whitespace-nowrap border-r-1 border-solid border-grey-200 h-auto"
              onClick={() => {
                delWarning(text);
              }}>
              删除
            </span>
            <span
              className="cursor-pointer py-0 px-8 leading-none whitespace-nowrap h-auto"
              onClick={() => {
                window.globalState.muState("history", {
                  type: "push",
                  pathname: "/batch_add_user/record/detail",
                  query: { id: text.id },
                });
              }}>
              详情
            </span>
          </div>
        );
      },
    },
  ];

  useEffect(() => {
    requestRecord();
  }, []);

  return (
    <div className="add-user-record w-full h-full flex flex-col">
      <Nav name="导入记录" router="/batch_add_user" />
      <div className="flex-1 p-16 overflow-y-auto scrollY">
        <Table
          columns={columns}
          loading={loding}
          dataSource={initFormData}
          pagination={false}
          className="mt-16"
          locale={{
            emptyText: (
              <div>
                <img
                  className="m-auto"
                  alt=""
                  src="https://assets.weibanzhushou.com/web/we-work-webapp/group-manage_search-empty.294f614b38df.svg"
                />
                <p>没有搜索到相关结果</p>
              </div>
            ),
          }}
        />
      </div>
      {page_total <= 1 ? null : (
        <Pagination
          className="text-right m-14"
          current={current}
          total={total}
          pageSize={limit}
          pageSizeOptions={["5", "10", "20", "50", "100"]}
          onChange={(page: any, pageSize: any) => {
            current = page;
            limit = pageSize;
            requestRecord();
          }}
          onShowSizeChange={(page, pageSize) => {
            current = page;
            limit = pageSize;
          }}
        />
      )}
    </div>
  );
};

export default AddUserRecord;
